const {
    tiUserName,
    tiPassWord,
} = require('./ti_config');
const {
    logger,
    saveScreenshot,
    checkCaptcha,
} = require('./util');

//登录流程
exports.webLogin = async page => {
    try {
        logger('开始登录');

        await page.goto('https://www.ti.com.cn/secure-link-forward/?gotoUrl=https%3A%2F%2Fwww.ti.com.cn%2F');
        await page.waitForSelector('input.u-width-full', {timeout: 60000});

        //如果已登录，可以跳过
        const check = await page.$('input.u-width-full');
        if (check) {
            logger('输入帐号');
            await page.type('input.u-width-full', tiUserName, { delay: 100 });
            await page.waitForTimeout(2000);
            await page.click('#nextbutton');
            await page.waitForTimeout(3000);

            //输入密码
            logger('输入密码');
            await page.type('input[name=password]', tiPassWord, { delay: 100 });
            await page.waitForTimeout(2000);
            await page.click('#loginbutton');

            logger('等待登录结果');

            //等待登录完成
            await page.waitForSelector('#homepage-carousel', {
                timeout: 60000,
            });
            logger('登录成功');
            await page.waitForTimeout(5000);
        } else {
            logger('检测到已登录');
        }
    } catch(e) {
        logger('登录失败', page.url(), e);
        await saveScreenshot(page, 'login_fail');
        await checkCaptcha(page);
        return false;
    }
    return true;
}


